import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal } from 'antd';
import { toJS } from 'mobx';
import { Condition, getAdButtons } from './list/listCondition';
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools, WeaDialog, WeaBrowser, WeaInput } from 'ecCom';
import CustomerContactDialog from './dialog/customerContactDialog';
// import WorkPlan from "weaWorkplan"
// const WorkPlanCreate = WorkPlan.com.WorkPlanCreate;
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
@inject('contactStore')
@observer
class Contact extends React.Component {
  constructor(props) {
    super(props);
    window._crmTable = {
      reLoad: props.contactStore.reLoad,
    };
    this.state = {
      workplanLoaded: false,
    };
  }

  componentDidMount() {
    // if(window.weaWorkplan){
    // search 查询客户  monitor 客户监控  assign 客户分配  share 批量共享  hrmView?searchHrmId=186  人员卡片过来的  //report客户信息
    // report 客户信息
    this.doInit(this.props);
    // }else{
    // 异步加载别模块的静态资源
    if (window.weaWorkplan) {
      this.setState({ workplanLoaded: true });
    } else {
      eventRegister.loadModule('f_workplan', () => {
        // 加载成功
        // search 查询客户  monitor 客户监控  assign 客户分配  share 批量共享  hrmView?searchHrmId=186  人员卡片过来的  //report客户信息
        // report 客户信息
        this.setState({ workplanLoaded: true });
      }, () => {
        // 加载文件失败 的业务处理， 网络超时，没文件之类
        alert('加载日程模块失败，请联系系统管理员！');
      });
    }

    // }
  }
  doInit(props) {
    const { location, contactStore } = props;
    const { initDatas, doSearch, getRemindCount } = contactStore;
    const params = {};
    if (props.location.query) {
      params.tabtype = props.location.query.tabtype;
    }
    initDatas(params);
    // doSearch(params);
    getRemindCount();
  }
  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { contactStore } = nextProps;
      const { initDatas, doSearch, getRemindCount, resetTable } = contactStore;
      contactStore.clearStatus();
      const params = {};
      if (nextProps.location.query) {
        params.tabtype = nextProps.location.query.tabtype;
      }
      initDatas(params);
      doSearch(params);
      getRemindCount();
      resetTable();
    }
  }
  componentWillUnmount() {
    const { contactStore } = this.props;
    contactStore.clearStatus();
  }
  render() {
    const { contactStore } = this.props;
    let { title, loading, tableStore, showSearchAd, form, remindCount, detailTabKey, remindTableStore, crmContactStore, remindInfo, workPlanvisible, contactId, workPlanActiveKey, isInitFinish } = contactStore;
    // console.log("remindCount",toJS(remindCount))
    let c = 0;
    if (remindCount instanceof Object) {
      c = remindCount.remindCount;
    }
    title = getLabel(6082, '客户联系');
    const tabDatas = [{ key: 'info', title: getLabel(16405, '联系情况') }, { key: 'plan', title: getLabel(16402, '联系计划') }, { key: 'remind', title: `${`${getLabel(16403, '联系提醒')}(${c})`}` }];
    const formParams = form.getFormParams() || {};
    const account = WeaTools.ls.getJSONObj('theme-account');
    let WorkPlanCreate = {};
    if (window.weaWorkplan) {
      WorkPlanCreate = weaWorkplan.com.WorkPlanCreate;
    }
    return (
      isInitFinish ? <WeaRightMenu
        ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@pohsy0`}
        datas={this.getRightMenu()}
        onClick={this.onRightMenuClick.bind(this)}
        collectParams={{
          favname: title,
          favouritetype: 4,
          importantlevel: 1,
          objid: -1,
        }}
      >
        <WeaTop
          ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@s4cw5x`}
          title={title}
          loading={loading}
          icon={<i className="icon-coms-crm" />}
          iconBgcolor="#96358a"
          buttonSpace={10}
          showDropIcon
          dropMenuDatas={this.getRightMenu()}
          onDropMenuClick={this.onRightMenuClick.bind(this)}
        >
          <WeaTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@2r3q9d`}
            buttons={this.getButtons(this.props.ecId || '')}
            buttonsAd={getAdButtons(contactStore, this.props.ecId || '')}
            searchType={detailTabKey != 'remind' && ['base', 'advanced']}
            searchsBaseValue={formParams.description}
            setShowSearchAd={(bool) => { contactStore.setShowSearchAd(bool); }}
            hideSearchAd={() => contactStore.setShowSearchAd(false)}
            searchsAd={<Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@zx5he2`} listStore={contactStore} form={form} onEnterSearch={this.onEnterSearch} />}
            showSearchAd={showSearchAd}
            onSearch={(v) => { contactStore.doSearch(); }}
            onSearchChange={(v) => {
              if (contactStore.form.has('description')) {
                contactStore.appendFormFields({ description: { value: v } });
              } else {
                contactStore.form.add(v, { key: 'description' });
              }
            }}
            selectedKey={detailTabKey}
            keyParam="key" // 主键
            onChange={this.changeData.bind(this)}
            datas={tabDatas}
          />
          {
            detailTabKey !== 'remind' ?
              <WeaTable
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@dujtg7`}
                comsWeaTableStore={tableStore}
                hasOrder
                needScroll
                onOperatesClick={this.onOperatesClick.bind(this)}
                getColumns={c => this.reRenderColumns(c)}
              /> :
              <WeaTable
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@hy1u68`}
                comsWeaTableStore={remindTableStore}
                hasOrder
                needScroll
                onOperatesClick={this.onOperatesClick.bind(this)}
              />
          }
          <CustomerContactDialog ecId={`${this && this.props && this.props.ecId || ''}_CustomerContactDialog@2ensa9`} ref="customerContact" crmContactStore={crmContactStore} contentStore={contactStore} />
        </WeaTop>
        {this.state.workplanLoaded && window.weaWorkplan && (
          <WorkPlanCreate
            ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@uug7mz`}
            type={'preview'}// 新建为'create',查看为'preview',编辑edit,共享share
            visible={workPlanvisible}// 显隐受控
            doClose={() => { contactStore.setWorkPlanVisible(false); }}// 关闭回调
            onlyClose={() => { contactStore.setWorkPlanVisible(false); }}// 关闭回调,只做关闭操作
            workPlanId={contactId} // 日程id，1查看日程时用到
            createConditionParams={[]}// 创建的默认值日期和时间,没有传[]
            activeKey={workPlanActiveKey} // 查看页面显示的面板1是基本信息，7是相关交流
            changeTab={(key) => { contactStore.changeWorkPlanTab(key); }}// 查看页面切换面板的回调
            selectUser={account && account.userid}// 新建日程的创建人id
            workPlanTypeOptions={3}// 客户模块的新建日程，普通新建传'',客户新建传3
            crmIDs={[]}// 通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
            description={''}
          />
        )}
      </WeaRightMenu> : null
    );
  }
  reRenderColumns(columns) {
    const that = this;
    columns.forEach((c) => {
      if (c.dataIndex == 'name') {
        c.render = function (text, record) {
          return <span className="nowrap crm-cursor-pointer"><a onClick={() => that.viewWorkPlan(record.randomFieldId)}>{record.name}</a></span>;
        };
      } else {
        c.render = function (text, record) {
          const valueSpan = record[`${c.dataIndex}span`] !== undefined ? record[`${c.dataIndex}span`] : record[c.dataIndex];
          return <span dangerouslySetInnerHTML={{ __html: valueSpan }} />;
        };
      }
    });
    return columns;
  }
  getRightMenu() {
    const { detailTabKey } = this.props.contactStore;
    const btns = [];
    { detailTabKey != 'remind' && btns.push({
    		icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
      key: 0,
    }); }
    btns.push({
    		icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
      key: 1,
    });

    detailTabKey === 'info' && btns.push({
    		icon: <i className="icon-coms-download2" />,
      content: getLabel(128713, 'EXCEL导入'),
      key: 2,
    });
    detailTabKey === 'info' && btns.push({
    		icon: <i className="icon-coms-upload" />,
      content: getLabel(81272, '导出全部'),
      key: 3,
    });
    detailTabKey === 'info' && btns.push({
    		icon: <i className="icon-coms-upload" />,
      content: getLabel(516118, '导出当前页'),
      key: 4,
    	});
    	return btns;
  }
  onRightMenuClick(key) {
    const { contactStore } = this.props;
    if (key == '0') {
      contactStore.doSearch();
    }
    if (key == '1') {
      contactStore.onShowColumn();
    }
    if (key == '2') {
      window.open('/spa/crm/static/index.html#/main/crm/contactImp');
    }
    if (key == '3') {
      contactStore.doExport();
    }

    if (key == '4') {
      contactStore.doExportCurrent();
    }
  }
  getButtons(ecId) {
    const { detailTabKey, tableStore, finishWorkPlan } = this.props.contactStore;
    const { selectedRowKeys } = tableStore;
    const btnArr = [];
    {
      detailTabKey == 'plan' &&
            btnArr.push(<Button
              ecId={`${ecId}_Button@x1wyni@plan`}
              type="primary"
              disabled={!(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`)}
              onClick={() => { finishWorkPlan({ planIds: `${toJS(selectedRowKeys)}` }); }}
            >{getLabel(555, '完成')}</Button>);
    }

    detailTabKey == 'info' &&
        btnArr.push(<Button
          ecId={`${ecId}_Button@xztspw@info`}
          type="primary"
          onClick={() => { window.open('/spa/crm/static/index.html#/main/crm/contactImp'); }}
        >{getLabel(128713, 'EXCEL导入')}</Button>);
    return btnArr;
  }
  changeData(key) {
    const { changeTab } = this.props.contactStore;
    changeTab(key);
  }
  onOperatesClick(record, index, operate, flag) {
    const { finishWorkPlan } = this.props.contactStore;
    if (flag == '3') { // 客户联系
      this.refs.customerContact.setVisible(true, record.randomFieldId);
    }
    if (flag == '0') { // 完成
      finishWorkPlan({ planIds: record.randomFieldId });
    }
  }
    viewWorkPlan=(id) => {
      const { contactStore } = this.props;
      contactStore.setWorkPlanVisible(true, id);
    }

    onEnterSearch=() => {
      const { contactStore } = this.props;
      contactStore.doSearch();
      contactStore.setShowSearchAd(false);
    }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@250yq4`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(Contact);
